package com.example.day9_sqlite;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    MyHelper myHelper;
    SQLiteDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建数据库 位置/data/data/包名/databases文件夹
        myHelper = new MyHelper(this);
        database = myHelper.getWritableDatabase();
        findViewById(R.id.bt_insert).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insert();
            }
        });
        findViewById(R.id.bt_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                select();
            }
        });
        findViewById(R.id.bt_update).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                update();
            }
        });
        findViewById(R.id.bt_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delete();
            }
        });
    }
    //删除
    private void delete() {
        database.execSQL("delete from song where id = ?",new String[]{"3"});
    }
    //修改
    private void update() {
        database.execSQL("update song set name = ? where id = ?",new String[]{"霍元甲","2"});
    }
    //查询
    private void select() {
        //cursor:游标
        Cursor cursor = database.rawQuery("select * from song ", new String[]{});
        if(cursor != null){
            while (cursor.moveToNext()){
                int id = cursor.getInt(0);//0代表字段的下标
                String name = cursor.getString(1);
                Log.d("ytx", "id: "+id+"name:"+name);
            }
        }
    }
    //增加数据
    private void insert() {
        database.execSQL("insert into song values(?,?)",new String[]{null,"青花瓷1"});
        database.execSQL("insert into song values(?,?)",new String[]{null,"青花瓷2"});
        database.execSQL("insert into song values(?,?)",new String[]{null,"青花瓷3"});
        database.execSQL("insert into song values(?,?)",new String[]{null,"青花瓷4"});
    }
}
